package codeRandomThoughts.Test110平衡二叉树;

import codeRandomThoughts.utils.TreeNode;

//二刷
public class Solution3 {
    public boolean isBalanced(TreeNode root) {
        return getDepth(root) != -1;
    }

    public int getDepth(TreeNode root) {
        //递归终止条件
        if (root==null) return 0;

        //左子树高度
        int leftDepth = getDepth(root.left);
        //右子树高度
        int rightDepth = getDepth(root.right);

        //二叉树不平衡
        if (leftDepth==-1||rightDepth==-1) return -1;
        if (Math.abs(leftDepth-rightDepth)>1) return -1;

        //平衡时返回左右子树较大的那个高度加1
        return Math.max(leftDepth,rightDepth)+1;
    }
}
